<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\WatchBloodOxygen;
use app\common\model\WatchBloodPressure;
use app\common\model\WatchHeartRate;
use app\common\model\WatchSetting;
use fast\Date;
use think\Config;
use think\Db;

/**
 * 手表设置
 */
class UserDevice extends Api
{
    protected $noNeedLogin = ['getWatch','updateelectricfence'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //手表绑定


    //手表上行数据接收
    public function setWatch(){
        $deviceid = input('deviceid');
        $data = input('data/a');
        if(isset($data['invitor_mobile'])&&!empty($data['invitor_mobile'])){
            $userModel = new \app\common\model\User();
            $userItem = $userModel->where('mobile',$data['invitor_mobile'])->find();
            if(!empty($userItem)){
                $data['invitor_uid'] = $userItem['id'];
                unset($data['invitor_mobile']);
            }else{
                $this->error('管理员手机号还不是该平台用户');
            }
        }
        if(isset($data['sy_mobile'])&&!empty($data['sy_mobile'])){
            $userModel = new \app\common\model\User();
            $userItem = $userModel->where('mobile',$data['sy_mobile'])->find();
            if(!empty($userItem)){
                $data['sy_uid'] = $userItem['id'];
            }
            unset($data['sy_mobile']);
        }
        if(isset($data['subdstrict_id'])&&$data['subdstrict_id']==0&&isset($data['subdstrict_name'])&&!empty($data['subdstrict_name'])){
            $name = $data['subdstrict_name'];
            $subdstrictitem = Db::name('area_subdstrict')
                ->where(array(
                    'province_id'=>$data['province_id'],
                    'city_id'=>$data['city_id'],
                    'region_id'=>$data['region_id'],
                    'name'=>$name
                ))->find();
            if(!empty($subdstrictitem)){
                $data['subdstrict_id'] = $subdstrictitem['id'];
            }else{
                $subdstrict = [
                    'province_id'=>$data['province_id'],
                    'city_id'=>$data['city_id'],
                    'region_id'=>$data['region_id'],
                    'town_id2'=>$data['town_id2'],
                    'name'=>$name,
                ];
                $data['subdstrict_id'] = Db::name('area_subdstrict')->insertGetId($subdstrict);
            }
            unset($data['subdstrict_name']);
        }
        if(!empty($data)){
            //请求手表下行接口设置
            $url = 'http://yg.hxinwatch.com/sdkapi/api/push/hjk/setWatch.htm?deviceid='.$deviceid;
            $arr = ['pbname1','pbname2','pbname3','pbname4','pbname5','pbname6','pbname7','pbname8','pbname9','pbname10'];
            foreach ($data as $key=>$val){
                if(in_array($key,$arr)){

                    $val = urlencode(base64_encode($val));

                }
                if((in_array($key,array('medicinename1','medicinename2','medicinename3')))){
                    continue;
                }
                $url .= '&'.$key.'='.$val;
            }

            $res = getcurl($url);
            if($res['code']==200){
                if($res['data']['code']==200){error_reporting(0);
                    //查询是否存在设备信息
                    $WatchSettingModel = new WatchSetting();
                    $item = $WatchSettingModel->where('deviceid',$deviceid)->find();
                    //cash now score in
                    $watcharr = $item;
                    $subdarr = \app\common\model\AddressLocation::where('subdstrict_id',$watcharr['subdstrict_id']?:null)->where('free',0)->find();
                    $invitorarr = \app\common\model\AddressLocation::where('uid',$watcharr['invitor_uid'])->where('free',0)->find();
                    $packodrarr = \app\api\model\wanlshop\PackageOrder::where(['deviceid'=>$deviceid,'status'=>'paid'])->where('package_id','NEQ',1)->find();
                        if(empty($item)){//插入
                        $data['deviceid'] = $deviceid;
                        $WatchSettingModel->save($data);
                        //give msg mobile
                        if($data['book1']) \app\common\library\Sms::send($data['book1'], $deviceid, 'notice');
                        if($data['book2']) \app\common\library\Sms::send($data['book2'], $deviceid, 'notice');
                        if($data['book3']) \app\common\library\Sms::send($data['book3'], $deviceid, 'notice');
                        /*if($packodrarr && ($subdarr || $invitorarr)){error_reporting(0);
                            if($packodrarr['package_id'] == 2 || $packodrarr['package_id'] == 3){
                                $userid = $subdarr['uid'] ?: $watcharr['invitor_uid'];
                                $communiarr = \app\common\model\AddressLocation::alias('a')->join('user u','uid=u.id')->where('a.town_id',$watcharr['town_id2'])->where('free',0)->where('u.level',4)->find();
                                if($userid){
                                    if($packodrarr['package_id'] == 2){
                                        for($i=1;$i<37;$i++){
                                            model('app\common\model\MoneyLogmonth')->create([
                                                'user_id' => $userid,
                                                'deviceid' => $deviceid,
                                                'money' => $i==1?30.00:sprintf("%.2f", 120 / 35),
                                                'subdid' => $watcharr['subdstrict_id'],
                                                'subdadminid' => $subdarr['uid'] ?: 0,
                                                'typename' => 'admintor',
                                                'memo' => '岗位奖励',
                                                'month' => date('Ym',strtotime(date('Y-m').'-15') + $i*30*24*3600)
                                            ]);
                                        }
                                    }elseif($packodrarr['package_id'] == 3){
                                        for($i=1;$i<13;$i++){
                                            model('app\common\model\MoneyLogmonth')->create([
                                                'user_id' => $userid,
                                                'deviceid' => $deviceid,
                                                'money' => $i==1?50.00:sprintf("%.2f", 100 / 11),
                                                'subdid' => $watcharr['subdstrict_id'],
                                                'subdadminid' => $subdarr['uid'] ?: 0,
                                                'typename' => 'admintor',
                                                'memo' => '岗位奖励',
                                                'month' => date('Ym',strtotime(date('Y-m').'-15') + $i*30*24*3600)
                                            ]);
                                        }
                                    }
                                }

                                if($communiarr){
                                    model('app\common\model\MoneyLogmonth')->create([
                                        'user_id' => $communiarr['uid'],
                                        'deviceid' => $deviceid,
                                        'money' => 20,
                                        'subdid' => $watcharr['subdstrict_id'],
                                        'subdadminid' => $subdarr['uid'] ?: 0,
                                        'typename' => 'managetor',
                                        'memo' => '管理奖励',
                                        'month' => date('Ym',strtotime(date('Y-m').'-15') + $i*30*24*3600)
                                    ]);
                                }

                                for($i=1;$i<13;$i++){
                                    model('app\common\model\ScoreLogmonth')->create([
                                        'user_id' => $userid,
                                        'deviceid' => $deviceid,
                                        'score' => $packodrarr['package_id']==2?39:99,
                                        'subdid' => $watcharr['subdstrict_id'],
                                        'subdadminid' => $subdarr['uid'] ?: 0,
                                        'typename' => 'scoretor',
                                        'memo' => '获得积分',
                                        'month' => date('Ym',strtotime(date('Y-m').'-15') + $i*30*24*3600)
                                    ]);
                                }
                            }
                        }*/
                    }else{//修改
                        $WatchSettingModel->save($data,array('id'=>$item['id']));
                        if($data['book1'] && $item['book1'] != $data['book1'] && \app\common\model\Sms::where(['mobile' => $data['book1']])->count() < 20){
                            \app\common\library\Sms::send($data['book1'], $deviceid, 'notice');
                        }elseif($data['book2'] && $item['book2'] != $data['book2'] && \app\common\model\Sms::where(['mobile' => $data['book2']])->count() < 20){
                            \app\common\library\Sms::send($data['book2'], $deviceid, 'notice');
                        }elseif($data['book3'] && $item['book3'] != $data['book3'] && \app\common\model\Sms::where(['mobile' => $data['book3']])->count() < 20){
                            \app\common\library\Sms::send($data['book3'], $deviceid, 'notice');
                        }
                        //cash now
                        if($item['book1'] && $item['book2'] && !\app\common\model\MoneyLogmonth::where(['user_id'=>($subdarr['uid'] ?: $watcharr['invitor_uid']),'memo'=>'推荐时光会员-奖励'])->where('createtime', 'between time', [time()-2*86400, time()])->find()){
                            if($packodrarr['payamount'] && $watcharr['is_pay'] == 1 && ($subdarr || $invitorarr)){error_reporting(0);
                                if($packodrarr['package_id'] == 2 || $packodrarr['package_id'] == 3){
                                    $userid = $subdarr['uid'] ?: $watcharr['invitor_uid'];
                                    $communiarr = \app\common\model\AddressLocation::alias('a')->join('user u','uid=u.id')->where('a.town_id',$watcharr['town_id2'])->where('free',0)->where('u.level',4)->find();
                                    if($userid && !\app\common\model\MoneyLogmonth::where(['deviceid'=>$deviceid,'memo'=>'岗位奖励'/*,'status'=>1*/])->find()){
                                        if($packodrarr['package_id'] == 2){
                                            for($i=1;$i<37;$i++){
                                                model('app\common\model\MoneyLogmonth')->create([
                                                    'user_id' => $userid,
                                                    'deviceid' => $deviceid,
                                                    'money' => $i==1?30.00:sprintf("%.2f", 120 / 35),
                                                    'subdid' => $watcharr['subdstrict_id'],
                                                    'subdadminid' => $subdarr['uid'] ?: 0,
                                                    'typename' => 'admintor',
                                                    'memo' => '岗位奖励',
                                                    'month' => date('Ym',strtotime(date('Y-m').'-20') + ($i-1)*30*24*3600)
                                                ]);
                                            }
                                        }elseif($packodrarr['package_id'] == 3){
                                            for($i=1;$i<13;$i++){
                                                model('app\common\model\MoneyLogmonth')->create([
                                                    'user_id' => $userid,
                                                    'deviceid' => $deviceid,
                                                    'money' => $i==1?50.00:sprintf("%.2f", 100 / 11),
                                                    'subdid' => $watcharr['subdstrict_id'],
                                                    'subdadminid' => $subdarr['uid'] ?: 0,
                                                    'typename' => 'admintor',
                                                    'memo' => '岗位奖励',
                                                    'month' => date('Ym',strtotime(date('Y-m').'-15') + $i*30*24*3600)
                                                ]);
                                            }
                                        }
                                    }

                                    if($communiarr && !\app\common\model\MoneyLogmonth::where(['deviceid'=>$deviceid,'memo'=>'管理奖励'/*,'status'=>1*/])->find()){
                                        model('app\common\model\MoneyLogmonth')->create([
                                            'user_id' => $communiarr['uid'],
                                            'deviceid' => $deviceid,
                                            'money' => 10,
                                            'subdid' => $watcharr['subdstrict_id'],
                                            'subdadminid' => $subdarr['uid'] ?: 0,
                                            'typename' => 'managetor',
                                            'memo' => '管理奖励',
                                            'month' => date('Ym',strtotime(date('Y-m').'-15') + 30*24*3600)
                                        ]);
                                    }

                                    if(!\app\common\model\ScoreLogmonth::where(['deviceid'=>$deviceid/*,'status'=>1*/])->find()){
                                        for($i=1;$i<13;$i++){
                                            model('app\common\model\ScoreLogmonth')->create([
                                                'user_id' => $data['sy_uid'],
                                                'deviceid' => $deviceid,
                                                'score' => $packodrarr['package_id']==2?39:99,
                                                'subdid' => $watcharr['subdstrict_id'],
                                                'subdadminid' => $subdarr['uid'] ?: 0,
                                                'typename' => 'scoretor',
                                                'memo' => '购买话费套餐获得积分',
                                                'month' => date('Ym',strtotime(date('Y-m').'-15') + $i*30*24*3600)
                                            ]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $this->success('设备参数修改成功');
                }else{
                    if($res['data']['msg']=='device is offline'){
                        $this->error('设备离线,操作失败');
                    }
                    if($res['data']['msg']=='need deviceid'){
                        $this->error('请联系管理员添加设备号');
                    }
                    $this->error($res['data']['msg']);
                }
            }else{
                $this->error('请求异常请联系管理员');
            }
            $this->success();
        }else{
            $this->error('设置数据不能为空');
        }

    }

    //获取手表设置
    public function getWatch(){
        $deviceid = input('deviceid');
        //查询手表设置信息
        $WatchSettingModel = new WatchSetting();
        $item = $WatchSettingModel->where(array('deviceid'=>$deviceid))->find();

        $starttime = Date::unixtime('day', -7, 'begin');
        $endtime = time();
        $heartRateModel = new WatchHeartRate();//心率
        $maxheartrate = $heartRateModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->max('value');
        $minheartrate = $heartRateModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->min('value');

        $WatchBloodOxygenModel = new WatchBloodOxygen();//血氧
        $bloodoxmax = $WatchBloodOxygenModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->max('value');
        $bloodoxmin = $WatchBloodOxygenModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->min('value');

        $WatchBloodPressureModel = new WatchBloodPressure();//血压
        $bphighmax = $WatchBloodPressureModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->max('max_value');
        $bphighmin = $WatchBloodPressureModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->min('max_value');

        $bplowmax = $WatchBloodPressureModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->max('min_value');
        $bplowmin = $WatchBloodPressureModel->where('deviceid',$deviceid)->where('createtime', 'between time', [$starttime, $endtime])->min('min_value');
        $setdata = [
           'maxheartrate'=>$maxheartrate,
            'minheartrate'=>$minheartrate,
            'bloodoxmax'=>$bloodoxmax,
            'bloodoxmin'=>$bloodoxmin,
            'bphighmax'=>$bphighmax,
            'bphighmin'=>$bphighmin,
            'bplowmax'=>$bplowmax,
            'bplowmin'=>$bplowmin,
        ];
        $url = 'http://yg.hxinwatch.com/sdkapi/api/push/hjk/setWatch.htm?deviceid='.$deviceid;
        foreach ($setdata as $key=>$val){
            $url .= '&'.$key.'='.$val;
        }
        $res = getcurl($url);
        if($res['code']==200){
            if($res['data']['code']==200){
                //查询是否存在设备信息
                $WatchSettingModel = new WatchSetting();
                $item = $WatchSettingModel->where('deviceid',$deviceid)->find();
                if(empty($item)){//插入
                    $data['deviceid'] = $deviceid;
                    $WatchSettingModel->save($setdata);
                }else{//修改
                    $WatchSettingModel->save($setdata,array('id'=>$item['id']));
                }
            }
            $item['maxheartrate']=$maxheartrate;
            $item['minheartrate']=$minheartrate;
            $item['bloodoxmax']=$bloodoxmax;
            $item['bloodoxmin']=$bloodoxmin;
            $item['bphighmax']=$bphighmax;
            $item['bphighmin']=$bphighmin;
            $item['bplowmax']=$bplowmax;
            $item['bplowmin']=$bplowmin;
        }
        //获取手表绑定的手机号
        if(!empty($item['invitor_uid'])){
            $invitor = Db::name('user')->where('id',$item['invitor_uid'])->find();
            $item['invitor_mobile'] = $invitor['mobile'];
        }
        if(!empty($item['sy_uid'])){
            $invitor = Db::name('user')->where('id',$item['sy_uid'])->find();
            $item['sy_mobile'] = $invitor['mobile'];
        }
        $this->success('获取设备参数成功',$item);
    }

    //设置电子围栏
    public function updateelectricfence(){
        $deviceid = input('deviceid');
        $data = input('data/a');
        //查询是否存在设备信息
        $WatchSettingModel = new WatchSetting();
        $item = $WatchSettingModel->where('deviceid',$deviceid)->find();
        if(empty($item)){//插入
            $this->error('手表设备号未录入后台系统');
        }
        $url = 'http://yg.hxinwatch.com/sdkapi/api/push/hjk/updateelectricfence.htm?deviceid='.$deviceid;
        foreach ($data as $key=>$val){
            $url .= '&'.$key.'='.$val;
        }
      $res = curl_request($url,false,[],true);
        if($res['code']==200){
            if($res['data']['code']==200){
                $WatchSettingModel->save($data,array('id'=>$item['id']));
                $this->success('电子围栏设置成功');
            }else{
                if($res['data']['msg']=='device is offline'){
                    $this->error('设备离线,操作失败');
                }
                if($res['data']['msg']=='need deviceid'){
                    $this->error('请联系管理员添加设备号');
                }
                $this->error($res['data']['msg']);
            }
        }else{
            $this->error('请求异常请联系管理员');
        }
    }



}
